package flex.cc.fenfa.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.core.utils.RequestUtil;
import flex.cc.fenfa.dao.RuleMainDao;
import flex.cc.fenfa.dao.RuleServicerDao;
import flex.cc.fenfa.dto.RuleChannelEntity;
import flex.cc.fenfa.dto.RuleMainEntity;
import flex.cc.fenfa.dto.RuleServicerEntity;
import flex.cc.fenfa.service.RuleChannelService;
import flex.cc.fenfa.service.RuleCountService;
import flex.cc.fenfa.service.RuleMainService;
import flex.cc.uac.entity.UacUserEntity;

/**
*
* @author WANGCONG
* 2021年10月12日下午3:20:58
* @desc 分发规则实现层
*/
@Service("ruleMainService")
@Transactional(rollbackFor = Exception.class)
public class RuleMainServiceImpl extends ServiceImpl<RuleMainDao, RuleMainEntity> implements RuleMainService{

	@Resource
	private RuleMainDao ruleMainDao;
	@Resource
	private RuleServicerDao servicerDao;
	@Resource
	private RuleChannelService channelService;
	@Resource
	private RuleCountService ruleCountService;
	
	/**
	*
	* @author WANGCONG
	* 2021年10月12日下午3:35:28
	* @desc 分发规则状态切换
	*/
	@Override
	public boolean modifyRuleStatus(RuleMainEntity ruleDto, LoginAuthDto loginAuthDto) {
		ruleDto.setUpdater(loginAuthDto.getLoginName());
		ruleDto.setUpdateTime(new Date());
		return ruleMainDao.modifyRuleStatus(ruleDto);
	}

	/**
	*
	* @author WANGCONG
	* 2021年10月12日下午4:05:02
	* @desc 分页查询规则
	*/
	@Override
	public IPage<RuleMainEntity> queryListWithPage(RuleMainEntity ruleDto) {
		Page<UacUserEntity> page = new Page<>(ruleDto.getPageNum(),ruleDto.getPageSize());
		IPage<RuleMainEntity> pageData=ruleMainDao.queryListWithPage(page, ruleDto);
		return pageData;
	}

	/**
	 * 
	 * @author WANGCONG
	 * 2021年10月13日上午9:02:19
	 * @desc 根据规则名称查看数量，校验规则名称唯一性
	 */
	@Override
	public int findCountByRuleName(RuleMainEntity vo) {
		return ruleMainDao.findCountByRuleName(vo);
	}

	/**
	 * 
	 * @author WANGCONG
	 * 2021年10月13日上午9:06:28
	 * @desc 规则信息保存
	 */
	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void save(Map<String, Object> reqVo) {
		LoginAuthDto loginUser = RequestUtil.getLoginUser();
		
		String ruleId = PublicUtil.isNotEmpty(reqVo.get("ruleId")) ? reqVo.get("ruleId").toString() : null;
        String ruleName = PublicUtil.isNotEmpty(reqVo.get("ruleName")) ? reqVo.get("ruleName").toString() : null;
        
        RuleMainEntity mainVo = new RuleMainEntity();
		LinkedHashMap<String, String> addrMap = (LinkedHashMap)reqVo.get("addrCounty");
		StringBuffer provinceCodeBuffer = new StringBuffer();
		StringBuffer provinceNameBuffer = new StringBuffer();
		StringBuffer cityCodeBuffer = new StringBuffer();
		StringBuffer cityNameBuffer = new StringBuffer();
		StringBuffer areaCodeBuffer = new StringBuffer();
		StringBuffer areaNameBuffer = new StringBuffer();
        if (PublicUtil.isNotEmpty(addrMap)) {
        	String provinces = addrMap.get("province");
        	if(StringUtils.isNotEmpty(provinces)){
        		String[] provincesArrs = provinces.split(",");
        		for(int i=0; i<provincesArrs.length; i++){
        			String[] provincesArr = provincesArrs[i].split("-");
        			provinceCodeBuffer.append(provincesArr[0]).append(",");
    				provinceNameBuffer.append(provincesArr[1]).append(",");
        		}
            }
        	String citys = addrMap.get("city");
        	if(StringUtils.isNotEmpty(citys)){
        		String[] citysArrs = citys.split(",");
        		for(int i=0; i<citysArrs.length; i++){
        			String[] citysArr = citysArrs[i].split("-");
        			cityCodeBuffer.append(citysArr[0]).append(",");
    				cityNameBuffer.append(citysArr[1]).append(",");
        		}
            }
        	String areas = addrMap.get("area");
        	if(StringUtils.isNotEmpty(areas)){
        		String[] areasArrs = areas.split(",");
        		for(int i=0; i<areasArrs.length; i++){
        			String[] areaArr = areasArrs[i].split("-");
        			areaCodeBuffer.append(areaArr[0]).append(",");
    				areaNameBuffer.append(areaArr[1]).append(",");
        		}
            }
        }
        mainVo.setProvince(provinceNameBuffer!=null && provinceNameBuffer.length()>0 ? provinceNameBuffer.substring(0, provinceNameBuffer.length()-1) : null);
    	mainVo.setProvinceCode(provinceCodeBuffer!=null && provinceCodeBuffer.length()>0 ? provinceCodeBuffer.substring(0, provinceCodeBuffer.length()-1) : null);
    	mainVo.setCity(cityNameBuffer.length()>0 ? cityNameBuffer.substring(0, cityNameBuffer.length()-1) : null);
    	mainVo.setCityCode(cityCodeBuffer.length()>0 ? cityCodeBuffer.substring(0, cityCodeBuffer.length()-1) : null);
    	mainVo.setArea(areaNameBuffer.length()>0 ? areaNameBuffer.substring(0, areaNameBuffer.length()-1) : null);
    	mainVo.setAreaCode(areaCodeBuffer.length()>0 ? areaCodeBuffer.substring(0, areaCodeBuffer.length()-1) : null);
    	
        String channelId = PublicUtil.isNotEmpty(reqVo.get("channelId")) ? reqVo.get("channelId").toString() : null;
        channelId = channelId.substring(1, channelId.length()-1).replace(" ","");
        //服务商和权重对应信息
        String servicerId = PublicUtil.isNotEmpty(reqVo.get("servicerId")) ? reqVo.get("servicerId").toString() : null;
        String weight = PublicUtil.isNotEmpty(reqVo.get("weightArr")) ? reqVo.get("weightArr").toString() : null;
        servicerId = servicerId.substring(1, servicerId.length()-1).replace(" ","");
        weight = weight.substring(1, weight.length()-1).replace(" ","");
        
        if(PublicUtil.isEmpty(ruleId)){//新增
        	ruleId = UUID.randomUUID().toString().replace("-", "");
        	mainVo.setRuleId(ruleId);
        	mainVo.setRuleName(ruleName);
        	mainVo.setChannelId(channelId);
        	String serviceItem = PublicUtil.isNotEmpty(reqVo.get("serviceItem")) ? reqVo.get("serviceItem").toString() : null;
        	serviceItem = serviceItem.contains("[")?serviceItem.substring(1, serviceItem.length()-1).replace(" ",""):serviceItem;
        	mainVo.setServiceItem(serviceItem);
        	mainVo.setStatus(0);//状态默认启用
        	mainVo.setCreater(loginUser.getUserCode());
        	mainVo.setCreateTime(new Date());
        	mainVo.setUpdater(loginUser.getUserCode());
        	mainVo.setUpdateTime(new Date());
        	mainVo.setIsDelete(0);
        	ruleMainDao.insert(mainVo);
        }else{//修改
        	mainVo.setRuleId(ruleId);
        	mainVo.setRuleName(ruleName);
        	mainVo.setChannelId(channelId);
        	String serviceItem = PublicUtil.isNotEmpty(reqVo.get("serviceItem")) ? reqVo.get("serviceItem").toString() : null;
        	serviceItem = serviceItem.substring(1, serviceItem.length()-1).replace(" ","");
        	mainVo.setServiceItem(serviceItem);
        	mainVo.setUpdater(loginUser.getUserCode());
        	mainVo.setUpdateTime(new Date());
        	mainVo.setIsDelete(0);
        	ruleMainDao.update(mainVo);
        	//更新规则后，将计数重置
        	ruleCountService.updateVersionByRuleId(ruleId);
        	servicerDao.deleteByRuleId(ruleId);
        	channelService.delByRuleId(ruleId);
        }
        List<RuleChannelEntity> channelList = new ArrayList<RuleChannelEntity>();
        for(int i=0; i<channelId.split(",").length; i++){
        	RuleChannelEntity channelVo = new RuleChannelEntity();
        	channelVo.setRuleId(ruleId);
        	channelVo.setChannelId(channelId.split(",")[i]);
        	channelList.add(channelVo);
        }
		channelService.insertBatch(channelList);
		List<RuleServicerEntity> servicerList = new ArrayList<RuleServicerEntity>();
        String[] servicerArr = servicerId.split(",");
        String[] weightArr = weight.split(",");
        for(int i=0; i<servicerArr.length; i++){
        	String current_weight = weightArr[i];
        	if("0".equals(current_weight) || PublicUtil.isEmpty(current_weight)){
        		continue;
        	}
        	RuleServicerEntity servicerVo = new RuleServicerEntity();
        	servicerVo.setDataId(UUID.randomUUID().toString().replace("-", ""));
        	servicerVo.setRuleId(ruleId);
        	servicerVo.setServiceId(servicerArr[i]);
        	servicerVo.setWeight(current_weight);
        	servicerList.add(servicerVo);
        }
        servicerDao.insertBatch(servicerList);
	}

	/**
	 * 
	 * @author WANGCONG
	 * 2021年10月14日下午1:55:41
	 * @desc 根据规则Id查询
	 */
	@Override
	public RuleMainEntity queryByRuleId(String ruleId) {
		return ruleMainDao.queryByRuleId(ruleId);
	}

	/**
	 * 
	 * @author WANGCONG
	 * 2021年10月17日下午5:37:06
	 * @desc 根据渠道方、省市区、服务类型匹配分发规则
	 */
	@Override
	public RuleMainEntity choiceServicer(Map<String, Object> paramsMap) {
		return ruleMainDao.choiceServicer(paramsMap);
	}

	/**
	 * @description 根据救援商id查询对应的规则是否为空或者0%，用于禁用救援商时判断【2.2-服务包配置需求】
	 * @param serviceId 救援商id
	 * @return 对应的规则名称
	 * @author wkangle
	 * @time 2022/03/07 0007 10:00
	 * @exception/throws
	 */
	@Override
	public String queryRuleNamesByServiceId(String serviceId) {
		return ruleMainDao.queryRuleNamesByServiceId(serviceId);
	}


}
